package cn.shenshen.shop.web.controller;

import cn.shenshen.shop.domain.User;
import cn.shenshen.shop.redis.MemberKeyPrefix;
import cn.shenshen.shop.redis.RedisService;
import cn.shenshen.shop.service.IUserService;
import cn.shenshen.shop.util.Result;
import cn.shenshen.shop.web.vo.LoginVo;
import com.netflix.ribbon.proxy.annotation.Http;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * 用户登录控制器
 */
@RestController
@RequestMapping("token")
public class TokenController {

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisService redisService;


    @RequestMapping("login")
    public Result<Boolean> login(@Valid LoginVo loginVo, HttpServletResponse response){

        String token = userService.login(Long.valueOf(loginVo.getUsername()), loginVo.getPassword());

       // System.out.println("redisService : " + redisService);测试自定义redis

        //返回正确信息,把token写入到浏览器
        Cookie cookie = new Cookie("USER_TOKEN", token);
        cookie.setDomain("localhost");
        cookie.setPath("/");
        cookie.setMaxAge(MemberKeyPrefix.USER_TOKEN.getExpireSeconds());
        response.addCookie(cookie);
        return Result.success(true);
    }

    @RequestMapping("getCurrentUser")
    public Result<User> getCurrentUser(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if (cookies==null){
            return Result.success(null);
        }
        for (Cookie cookie : cookies) {
            if ("USER_TOKEN".equals(cookie.getName())){
                String token = cookie.getValue();
                User user = redisService.get(MemberKeyPrefix.USER_TOKEN, token, User.class);
                return Result.success(user);
            }
        }

        //成功返回的信息
        return Result.success(null);

    }

}
